﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
//using System.Windows.Shapes;
//
using System.Collections.ObjectModel;
//
using System.IO;
using System.Configuration;
using System.ComponentModel;
using System.Windows.Interop;
//
// Mp3Cleaner, Copyright Mirosław M. Mączka.  All Rights Reserved. This code released under the terms of the Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
//
namespace Mp3Cleaner
{

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //
        //
        public ObservableCollection<CData> LD = new ObservableCollection<CData>();
        //
        //public static string StartDirector y = @"D:\INET\USB\ok\Caterina Valente-Ok_nt album";
        public static string[] DefaultMusicFilesExtensions = { @".mp3", @".wma", @".ogg", @".mp4", @".m4a", @".wav", @".flac", @".ra", @".ape", @".mpc", @"" };
        public static string[] MusicFilesExtensions = DefaultMusicFilesExtensions;//należy przywrócić default przed odczytem katalogu
        //public static string StartDirectory = @"D:\INET\USB\ok\Madredeus - Faluas Do Tejo (2005) - World";
        public static string StartDirectory = @"";
        //
        // Struktura katalogów: .../Artist/Album/*.mp3
        public static string DirAlbum = "";// [Year] Album
        public static string DirArtist = ""; // Artist
        //
        // ustawiany, gdy numer ścieżki został * x00
        public bool isTrackMuliplied = false;
        //
        private bool exitAfterWrite = false;// do użycia w batchu
        private bool fullScreen = false;// do użycia w batchu
        //
        //
        //
        //
        //
        public MainWindow()
        {
            //
            Utils.RenameHelpFiles();
            //
            InitializeComponent();
            //
            loadLocale();
            //
            checkFirstTime();
            //
            window1.Title = getVersionInfo();
            //
            if (!Utils.isEmpty(Environment.GetEnvironmentVariable("EXIT-AFTER-WRITE")))
            {
                exitAfterWrite = true;
            }
            if (!Utils.isEmpty(Environment.GetEnvironmentVariable("FULL-SCREEN")))
            {
                fullScreen = true;
            }
            //
            string[] cmdArgs = Environment.GetCommandLineArgs();
            string s = Environment.CommandLine;
            //MusicFilesExtensions = DefaultMusicFilesExtensions;
            if (2 == cmdArgs.GetLength(0))
            {
                string targetDir = cmdArgs[1];
                if (!Directory.Exists(targetDir))//zapewne to plik
                {
                    MusicFilesExtensions = new string[] { Path.GetExtension(targetDir) };
                    targetDir = Path.GetDirectoryName(targetDir);
                }
                if (Directory.Exists(targetDir))
                {
                    StartDirectory = targetDir;
                    WaitingTooLong wtl = new WaitingTooLong(5);
                    window1.IsEnabled = false;
                    using (new StackedCursorOverride(Cursors.Wait))
                    {

                        loadDir();
                    }
                    window1.IsEnabled = true;
                    wtl.isTooLongBeep(new WindowInteropHelper(this).Handle);
                    afterLoad(true);
                }
                setInfoFromPath(StartDirectory);
            }
            else
            {
                // informacja dla ukrytego przycisku [Navigate]
                StartDirectory = Properties.Settings.Default.pathNavigate;
            }
            //
            //
            if (fullScreen)
            {
                window1.Topmost = true;
                window1.WindowState = System.Windows.WindowState.Maximized;
            }
            //
            //this.toolTip1.SetToolTip(this, "toolTip");
            //
            dataGrid1.ItemsSource = LD;
        }

        private void window1_Closed(object sender, EventArgs e)
        {
            Properties.Settings.Default.Save();
        }

        private void buttonDoClean_Click(object sender, RoutedEventArgs e)
        {
            using (new StackedCursorOverride(Cursors.Wait))
            {
                DoClean();
                CData.Sort(LD);
            }
            //

            afterClean();
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        private void buttonWrite_Click(object sender, RoutedEventArgs e)
        {
            WaitingTooLong wtl = new WaitingTooLong(5);
            window1.IsEnabled = false;
            using (new StackedCursorOverride(Cursors.Wait))
            {
                DoWrite();
            }
            window1.IsEnabled = true;
            wtl.isTooLongBeep(new WindowInteropHelper(this).Handle);
            afterWrite();
            if (exitAfterWrite)
            {
                //do użycia w batchu, katalog po katalogu, z listy
                this.Close();
            }
            //
        }

        private void buttonRemove_Click(object sender, RoutedEventArgs e)
        {
            DoRemove();
        }

        private void buttonCpTrack_Click(object sender, RoutedEventArgs e)
        {
            Copy_tagTrack_2_FileTrack();
        }

        private void buttonCpName_Click(object sender, RoutedEventArgs e)
        {
            Copy_tagTitle_2_FileName();
        }

        private void buttonCombineTagTitle_Click(object sender, RoutedEventArgs e)
        {
            
            //if (0 == (Control.ModifierKeys & (Key.LeftShift | Key.RightShift)))
            if(!Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
            {
                Concat_tagArtisttagTitle2FileName(false);
            }
            else
            {
                Concat_tagArtisttagTitle2FileName(true);
            }
        }

        private void button2tagTrack_Click(object sender, RoutedEventArgs e)
        {
            Copy_FileTrack_2_tagTrack();
        }

        private void button2tagTitle_Click(object sender, RoutedEventArgs e)
        {
            Copy_FileName_2_tagTitle();
        }

        private void buttonSplitTagTitle_Click(object sender, RoutedEventArgs e)
        {
            //if (0 == (Control.ModifierKeys & Keys.Shift))
            if(!Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
            {
                Split_tagTitle2tagTitletagAuthor(false);
            }
            else
            {
                Split_tagTitle2tagTitletagAuthor(true);
            }
        }

        private void buttonConvertToWP_Click(object sender, RoutedEventArgs e)
        {
            makeWindowsPhoneCompatible();
        }

        private void buttonSetTagArtist_Click(object sender, RoutedEventArgs e)
        {
            string artist = CaseUtils.ToCamelIfNeeded(DirArtist);
            if ("" == artist)
            {
                artist = (from x in LD where "" != x.tagArtist select x.tagArtist).FirstOrDefault();
                if (null == artist) artist = "";
            }
            //
            artist = Utils.swapThe(artist);
            //
            DialogBox ibr = new DialogBox() { Title = "tagArtist", Label = "Artist:", Text = artist };
            ibr.ShowDialog();
            if (!(bool)ibr.DialogResult) return;
            //
            SetTagArtist(ibr.Text);
        }

        private void buttonSetTagAlbum_Click(object sender, RoutedEventArgs e)
        {
            string album = CaseUtils.ToCamelIfNeeded(Utils.GetWithoutYearFromString(DirAlbum).Trim());
            if ("" == album)
            {
                album = (from x in LD where "" != x.tagAlbum select x.tagAlbum).FirstOrDefault();
                if (null == album) album = "";
            }
            //
            DialogBox ibr = new DialogBox() { Title = "tagAlbum", Label = "Album:", Text = album };
            ibr.ShowDialog();
            if (!(bool)ibr.DialogResult) return;

            SetTagAlbum(ibr.Text);
        }

        private void buttonSetTagYear_Click(object sender, RoutedEventArgs e)
        {
            string year = Utils.GetYearFromString(DirAlbum);
            if ("" == year)
            {
                year = (from x in LD where "" != x.tagYear select x.tagYear).FirstOrDefault();
                if (null == year) year = "";
            }
            //
            DialogBox ibr = new DialogBox() { Title = "tagYear", Label = "Year:", Text = year };
            ibr.ShowDialog();
            if (!(bool)ibr.DialogResult) return;
            //
            SetTagYear(verifyNumber(ibr.Text, 4));
        }

        private void buttonSetTagGenre_Click(object sender, RoutedEventArgs e)
        {
            var genre = (from x in LD where "" != x.tagGenre select x.tagGenre).FirstOrDefault();
            if (null == genre) genre = "";
            //
            DialogBox ibr = new DialogBox() { Title = "tagGenre", Label = "Genre:", Text = genre };
            ibr.ShowDialog();
            if (!(bool)ibr.DialogResult) return;
            //
            SetTagGenre(ibr.Text);
        }
        //---------------------------------------------------------------------------------------------------------------------------------
        private void button_x00_Click(object sender, RoutedEventArgs e)
        {
            if (!Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
            {
                MultiplyTrackNumber(0, ((Button)sender).Tag.ToString());
            }
            else
            {
                MultiplyTrackNumber(4, ((Button)sender).Tag.ToString());
            }
            checkBox_RemoveCommon.IsChecked = false;
        }

        private void Help_Click(object sender, RoutedEventArgs e)
        {
            string hlp_en = "hlp-en.mht";
            try
            {
                string hlp = string.Format("help-{0}.mht", Utils.CurrentTwoLetterLanguage());
                //
                if (!File.Exists(hlp))
                {
                    if(!File.Exists(hlp_en))
                    {
                        return;
                    }
                    hlp = hlp_en;
                }
                System.Diagnostics.Process.Start(hlp);
            }
            catch (FileNotFoundException efnf)
            {
                ;
            }
        }

        //---------------------------------------------------------------------------------------------------------------------------------

    }
}
